<?php

class Session
{
	public static $LifeTime = 2592000; // = 60 * 60 * 24 * 30; ea. 30 days
	public static $Path = '/';
	public static $Domain = 'localhost';
	
	public static $Instance;
	
	public static function GetInstance( )
	{
		if( !isset( self::$Instance ) )
		{
			self::$Instance = new self( );
			self::$Instance->Start( );
		}
		return self::$Instance;
	}
	
	public $ID;
	public $Data;
	
	public function GetStorage( )
	{
		return new FileStorage( Modules::$Modules['/']->Path . '/ServerData/Session' );
	}
	
	// deprecated, see Start
	public function Init( )
	{
		$this->Start();
	}
	
	// starts the session
	public function Start( )
	{
		if( isset( $_COOKIE['SessionID'] ) )
		{
			$this->ID = $_COOKIE['SessionID'];
			$this->Load( );
		}
		else
		{
			$this->Create( );
		}
	}
	
	public function IsRoot( )
	{
		return strlen( $_SERVER['REQUEST_URI'] ) < 1 || strpos( $_SERVER['REQUEST_URI'], '/', 1 ) == false;
	}
	
	// creates a session 
	// must be done before headers are sent (cookie)
	public function Create( )
	{
		$this->Data = array( );
		if( $this->IsRoot( ) )
		{
			$this->Save( );
			setcookie( 'SessionID', $this->ID, time() + self::$LifeTime );//, self::$Path, self::$Domain );
		}
	}
	
	// load the data from the session file
	public function Load( )
	{
		if( $this->GetStorage( )->IsValid( $this->ID ) )
			$this->Data = unserialize( $this->GetStorage( )->Load( $this->ID ) );
		else
			$this->Data = array( );
	}
	
	public function Save( )
	{
		if( !isset( $this->ID ) )
		{
			$this->ID = $this->GetStorage( )->Save( serialize( $this->Data ) );
		}
		else
		{
			$this->GetStorage( )->Overwrite( $this->ID, serialize( $this->Data ) );
		}
	}
	
	public function Destroy( )
	{
		if( $this->IsRoot( ) )
		{
			$_COOKIE['SessionID'] = '';
			$Success = setcookie( 'SessionID', '',  time() - 7200 ); //, self::$Path, self::$Domain );
			if( $this->GetStorage( )->IsValid( $this->ID ) )
				$this->GetStorage( )->Delete( $this->ID );
			unset( $this->ID );
			unset( $this->Data );
		}
	}
	
	public function __get( $Key )
	{
		if( !isset( $this->Data[$Key] ) ) return null;
		return $this->Data[$Key];
	}
	
	public function __set( $Key, $Value )
	{
		$this->Data[$Key] = $Value;
	}
}

?>